﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Data;
using System.Globalization;

using OgilvyOne.Model;
using OgilvyOne.BLL;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;
using OgilvyOne.UKNow.DAL;
using OgilvyOne.UKNow.DALFactory;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using ECCIT;
using ECCIT.Data;

namespace OgilvyOne.UKNow.BLL
{
    public  class EventsTemplateType : CommonModel
    {
        public int LanguageID { get; set; }
        public EventsModel EventsModel { get; set; }

        public EventsTemplateType(CmsVo vo)
            : base(vo)
        {
            //html = html.Replace("<h2><img src=\"/cn/images/titlecollege.gif\" /></h2>", menupage.GetHealthLeftImg());
            if (vo is CmsVoWrapper)
            {
                this.LanguageID = ((CmsVoWrapper)vo).LanguageID;
                this.EventsModel = ((CmsVoWrapper)vo).EventsModel;
            }
        }
        /// <summary>
        /// 获取活动内容页的活动标题
        /// </summary>
        /// <returns></returns>
        public string GetEventsTitle() //GetEventsTitle为获取相关活动的标签值
        {
            //AccountController ac = new AccountController(LanguageID);
            //ac.EventInfo = this.EventsModel;
            string title = (this.EventsModel.Title == null) ? string.Empty : this.EventsModel.Title;
            return title;
        }

        public string GetEventsSubTitle()
        {
            string title = (this.EventsModel.SubTitle == null) ? string.Empty : this.EventsModel.SubTitle;
            return title + "<input type=hidden id='hdn_eventsId' value='" + this.EventsModel.ID + "'/>";
        }
        /// <summary>
        /// 获取活动内容页的活动城市
        /// </summary>
        /// <returns></returns>
        public string GetEventsCity() 
        {
            if (!this.EventsModel.City.HasValue) return string.Empty;

            DictionaryManageBLL bll = new DictionaryManageBLL();
            DictionaryManageModel model = bll.selectDictionary(this.EventsModel.City.Value);
            if (model == null) return string.Empty;

            if (this.LanguageID == (int)LanguageType.cn)
                return model.Cnname;
            else
                return model.Enname;
        }

        /// <summary>
        /// 获取活动内容页的活动日期
        /// </summary>
        /// <returns></returns>
        public string GetEventsDate()
        {
            if (this.EventsModel.LanguageID == (int)LanguageType.cn)
                return FormatEventsDate_Cn(this.EventsModel);
            else
                return FormatEventsDate_En(this.EventsModel);
        }

        private string FormatEventsDate_Cn(EventsModel model)
        {
            string joinChar = "  至  ";
            string startTime = FormatDate_Cn(model.StartTime);
            string endTime = FormatDate_Cn(model.EndTime);

            if (string.IsNullOrEmpty(startTime) && string.IsNullOrEmpty(endTime))
                return "敬请期待";
            else if (string.IsNullOrEmpty(startTime))
                return endTime;
            else if (string.IsNullOrEmpty(endTime))
                return startTime;
            else
            {
                if (model.StartTime.Value.Year == model.EndTime.Value.Year)
                    return startTime + joinChar + endTime.Substring(5);
                return startTime + joinChar + endTime;
            }
        }

        private string FormatEventsDate_En(EventsModel model)
        {
            string joinChar = "  to  ";
            string startTime = FormatDate_En(model.StartTime);
            string endTime = FormatDate_En(model.EndTime);

            if (string.IsNullOrEmpty(startTime) && string.IsNullOrEmpty(endTime))
                return "TBC";
            else if (string.IsNullOrEmpty(startTime))
                return endTime;
            else if (string.IsNullOrEmpty(endTime))
                return startTime;
            else
            {
                if (model.StartTime.Value.Year == model.EndTime.Value.Year)
                {
                    // 英文日期处理
                    if (model.StartTime.Value.Month != model.EndTime.Value.Month)
                    {
                        int index = startTime.IndexOf(" ", 3);  // 获取d-MMMM-yyyy中MMMM后的"-"字符的索引

                        return startTime.Substring(0, index) + joinChar + endTime;
                    }
                    else
                        return model.StartTime.Value.Day + joinChar + endTime;
                }
                return startTime + joinChar + endTime;
            }
        }

        private string FormatDate_En(DateTime? dateTime)
        {
            if (!dateTime.HasValue) return "";

            string sFirst = "";
            //string longFormatString = "d-MMMM-yyyy HH:mm";
            string shortFormatString = "d-MMMM-yyyy";
            CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");

            sFirst = dateTime.Value.ToString(shortFormatString, cultureInfo);
            int hour = dateTime.Value.Hour;
            int minute = dateTime.Value.Minute;
            if (dateTime.Value.Hour > 0 || dateTime.Value.Minute > 0)
            {
                string tt = (hour > 12) ? "p.m." : "a.m.";
                hour = (hour > 12) ? hour - 12 : hour;
                sFirst += " " + hour + "." + minute + " " + tt;
            }

            sFirst = sFirst.Replace("-", " ");
            return sFirst;
        }

        private string FormatDate_Cn(DateTime? dateTime)
        {
            if (!dateTime.HasValue) return "";

            string sFirst = "";
            string longFormatString = "yyyy年MM月dd日 HH:mm";
            string shortFormatString = "yyyy年MM月dd日";
            CultureInfo cultureInfo = null;

            string sStartTime = dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
            if (sStartTime.EndsWith(" 00:00:00"))
                sFirst = dateTime.Value.ToString(shortFormatString, cultureInfo);
            else
                sFirst = dateTime.Value.ToString(longFormatString, cultureInfo);

            return sFirst;
        }

        /// <summary>
        /// 获取活动内容页的活动地点
        /// </summary>
        /// <returns></returns>
        public string GetEventsAddress() 
        {
            string venue = this.EventsModel.Venue == null ? string.Empty : this.EventsModel.Venue;
            return venue;
        }

        private string GetRootDir()
        {
            if (this.LanguageID == (int)LanguageType.cn) 
                return "/cn";
            else
                return "/en";
        }

        public string GetEventsVenueImagePath()
        {
            if (string.IsNullOrEmpty(this.EventsModel.VenueImagePath)) return string.Empty;

            string s = string.Format("<a href='{4}/map.html?{0}={1}&{2}={3}?keepThis=true&TB_iframe=true&height=524&width=507' class='thickbox'><img src='{4}/images/btn_lookfor.gif' alt=''/></a>",
                "venue", this.EventsModel.Venue, "img", this.EventsModel.VenueImagePath, GetRootDir());

            return s;
        }

        /// <summary>
        /// 获取活动内容页的活动艺术形式
        /// </summary>
        /// <returns></returns>
        public string GetEventsArtform()
        {
            return this.EventsModel.ArtForm == null ? string.Empty : this.EventsModel.ArtForm.Name;
        }

        /// <summary>
        /// 获取活动内容页的活动详情
        /// </summary>
        /// <returns></returns>
        public string GetEventsDesc()
        {
            //return this.EventsModel.ShortDescription == null ? string.Empty : this.EventsModel.ShortDescription.Replace("<", "&lt;").Replace(">", "&gt;").Replace("\r\n", "<br/>");
            /*
             * 代码修改：
             * 修改日期：2012-03-22
             * 修改人员：刘扬
             * 修改原因：简介需要输出斜体，所以不能替换"<"和">"
             * */
            return this.EventsModel.ShortDescription == null ? string.Empty : this.EventsModel.ShortDescription.Replace("\r\n", "<br/>");
        }

        public string GetEventsMoreDetail()
        {
            if (!string.IsNullOrEmpty(this.EventsModel.Detail))
            {
                string s = "<script language='javascript'>$(function(){$('#wantmore img').click(function(){$('#morevent').slideToggle('slow'); return false;});});</script>" +
                    "<div id='wantmore'><a href='#'><img src='" + GetRootDir() + "/images/btn_event_more.gif' alt='' /></a></div>" +
                    "<div id='morevent'><h2><span>" + this.EventsModel.Detail + "</span></h2></div>";

                return s;
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取活动内容页的活动赞助商
        /// </summary>
        /// <returns></returns>
        public string GetEventsSponsor()
        {
            if (this.EventsModel.Sponsor == null)
            {
                return string.Empty;
            }
            else
            {
                ILanguage language = LanguageFactory.Create(this.LanguageID);
                string modelName = language.GetModelText(typeof(SponsorModel));
                return string.Format("<h2><span>{0}：</span>{1}</h2>", modelName, this.EventsModel.Sponsor.Name);
            }
        }

        /// <summary>
        /// 获取活动内容页的相关活动列表
        /// </summary>
        /// <returns></returns>
        public string GetEventsCorrelation()
        {
            if (vo.languageID==1033 && vo.Aid == 68)
            {
                string s = "";
            }

            IList<EventsModel> pl = new EventsBLL(this.LanguageID).GetRelatedEvents(vo.Aid, null);
            if (pl.Count == 0) return string.Empty;

            string text = (this.LanguageID == (int)LanguageType.en) ? "Events you might be also interested in" : "你也许对以下热门活动感兴趣";
            StringBuilder sb = new StringBuilder("<div class='interesting'>").Append(text).Append("</div><ul class='sortlist'>");
            string[] classes = new string[6];
            classes[0] = "yellow";
            classes[1] = "green";
            classes[2] = "purple";
            classes[3] = "blue";
            classes[4] = "red";
            classes[5] = "pink";

            for (int i = 0; i < pl.Count; i++)
            {
                EventsModel emodel = pl[i];
                string classValue = "";
                string cityName = "";
                if (emodel.City.HasValue)
                {
                    DictionaryManageModel city = Utility.DictionaryUtil.GetCityByID(emodel.City.Value);
                    if (city != null)
                        cityName = (this.LanguageID == (int)LanguageType.cn) ? city.Cnname : city.Enname;
                }

                string img = "/uploadfiles/image/" + emodel.ListImg;  //活动列表图
                string subTitle = "";
                if (emodel.SubTitle != null)
                {
                    int remaingLength = (this.LanguageID == (int)LanguageType.cn) ? 30 : 60;
                    if (emodel.SubTitle.Length > remaingLength)
                        subTitle = emodel.SubTitle.Substring(0, remaingLength) + "...";
                    else
                        subTitle = emodel.SubTitle;
                }
                classValue = classes[emodel.ArtFormID.Value - 1]; //取余数
                sb.Append("<li>");
                sb.Append("<a href=\"" + emodel.ID + ".html \" alt=\"" + emodel.Title + "\" title=\"" + emodel.ShortDescription + "\"><img src=\"" + img + "\" width=\"234\" height=\"114\" onerror=\"this.src='/cn/images/default_img.jpg';\"/></a>");
                sb.Append("<dl class=\"" + classValue + "\">");
                sb.Append("<dt>" + cityName + "</dt>");
                sb.Append("<dd>" + emodel.ArtForm.Name + "</dd>");
                sb.Append("</dl>");
                sb.Append("<acronym class=\"" + classValue + "\">" + ((emodel.LanguageID == (int)LanguageType.cn) ? FormatEventsDate_Cn(emodel) : FormatEventsDate_En(emodel)) + "</acronym>");
                sb.Append("<span><span><a href=\"" + emodel.ID + ".html\">" + emodel.Title + "</a></span><a href=\"" + emodel.ID + ".html\" alt=\"" + emodel.SubTitle + "\" title=\"" + emodel.SubTitle + "\">" + subTitle + "</a></span>");
                sb.Append("</li>");
            }
            sb.Append("</ul>");
            return sb.ToString();
        }

        /// <summary>
        /// 获取活动内容页的 上传的big图片(详情图片)
        /// </summary>
        /// <returns></returns>
        public string GetEventsImg()
        {
            StringBuilder sb = new StringBuilder();

            // 获取图片数据
            //IList<EventsImageModel> list = new EventsImageBLL(this.LanguageID).GetAllEventsImageModels(vo.Aid);
            int pageSize = 8;
            int currPageIndex = 0;
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currPageIndex, pageSize, null);
            PagingList list = new EventsBLL(this.LanguageID).GetUploadFilesByEventsID(vo.Aid, pagingParams);
            
            // 把记录总数作为隐藏域输出
            sb.AppendFormat("<input type='hidden' id='hdnTotalUploadFileCount' value='{0}'/>", list.Capacity);
            sb.AppendFormat("<input type='hidden' id='hdnCurrentTotalUploadFileCount' value='{0}'/>", list.List.Count);

            for (int i = 0; i < list.List.Count; i++)
            {
                UploadFileModel model = (UploadFileModel)list.List[i];

                string div_id = "image_sub-0" + (i + 1);
                
                sb.Append("<div id=\"" + div_id + "\">");
                if (model.FileType == 1)
                    sb.Append(RenderImage(model));
                else if (model.FileType == 2)
                    sb.Append(RenderVideo(model, i));
                else if (model.FileType == 3)
                    sb.Append(RenderAudio(model, i));
                sb.Append("<div class='word'></div>");
                sb.Append("</div>");
            }

            return sb.ToString();
        }

        private string RenderImage(UploadFileModel model)
        {
            string imgpath = "/uploadfiles/image/" + ((string.IsNullOrEmpty(model.Path) ? "default_slide_big_img.jpg" : model.Path));
            string s = string.Format("<img src=\"{0}\" alt=\"\" onerror='this.src=\"/uploadfiles/image/default_slide_big_img.jpg\"'/>", imgpath);
            return s;
        }

        private string RenderVideo(UploadFileModel model, int index)
        {
            //string s = string.Format("<embed id=\"motoFlash\" width=\"592\" height=\"356\" flashvars=\"URL=/uploadfiles/media/{0}\" wmode=\"transparent\" scale=\"noscale\" menu=\"false\" quality=\"high\" bgcolor=\"#ffffff\" name=\"motoFlash\" src=\"../swf/say.swf\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\"></embed>"
            //    , model.Path);
            string id = "homeAsset_" + model.ID;
            StringBuilder builder = new StringBuilder();
            builder.Append("<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" width=\"592\" height=\"356\" id=\"").Append(id).Append("\" align=\"middle\">");
            builder.Append("<param name=\"allowScriptAccess\" value=\"always\" />");
            builder.Append("<param name=\"allowFullScreen\" value=\"false\" />");
            builder.Append("<param name=\"movie\" value=\"/cn/swf/player.swf\" />");
            builder.Append("<param name=\"quality\" value=\"high\" />");
            builder.Append("<param name=\"bgcolor\" value=\"#ffffff\" />");
            builder.Append("<param name=\"wmode\" value=\"transparent\" />");
            //if (index == 0)
            //    builder.Append("<param name=\"flashVars\" value=\"url=/uploadfiles/media/" + model.Path + "\">");
            builder.Append("<embed src=\"/cn/swf/player.swf\" quality=\"high\" wmode=\"transparent\" bgcolor=\"#ffffff\" width=\"592\" height=\"356\" name=\"").Append(id).Append("\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_cn\" ");
            //if (index==0)
            //    builder.Append(" flashvars=\"url=/uploadfiles/media/").Append(model.Path).Append("\"");
            builder.Append("/>");
            builder.Append("</object>");
            return builder.ToString();
        }

        private string RenderAudio(UploadFileModel model, int index)
        {
            string id = "homeAsset_" + model.ID;
            StringBuilder builder = new StringBuilder();
            builder.Append("<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0\" width=\"592\" height=\"356\" id=\"").Append(id).Append("\" align=\"middle\">");
            builder.Append("<param name=\"allowScriptAccess\" value=\"always\" />");
            builder.Append("<param name=\"allowFullScreen\" value=\"false\" />");
            builder.Append("<param name=\"movie\" value=\"/cn/swf/simpleplayer.swf\" />");
            builder.Append("<param name=\"quality\" value=\"high\" />");
            builder.Append("<param name=\"bgcolor\" value=\"#ffffff\" />");
            builder.Append("<param name=\"wmode\" value=\"transparent\" />");
            //if (index == 0)
            //    builder.Append("<param name=\"flashVars\" value=\"url=/uploadfiles/media/" + model.Path + "\">");
            builder.Append("<embed src=\"/cn/swf/simpleplayer.swf\" quality=\"high\" wmode=\"transparent\" bgcolor=\"#ffffff\" width=\"592\" height=\"356\" name=\"").Append(id).Append("\" align=\"middle\" allowScriptAccess=\"always\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_cn\" ");
            //if (index==0)
            //    builder.Append(" flashvars=\"url=/uploadfiles/media/").Append(model.Path).Append("\"");
            builder.Append("/>");
            builder.Append("</object>");
            return builder.ToString();
        }

        /// <summary>
        /// 获取活动内容页的 上传的缩略图
        /// </summary>
        /// <returns></returns>
        public string GetEventsMinImg()
        {
            //IList<EventsImageModel> list = new EventsImageBLL(this.LanguageID).GetTop7EventsImageModels(vo.Aid);
            int pageSize = 8;
            int currPageIndex = 0;
            PagingParameter pagingParams = PagingParameterFactory.CreateInstance(true, currPageIndex, pageSize, null);
            PagingList list = new EventsBLL(this.LanguageID).GetUploadFilesByEventsID(vo.Aid, pagingParams);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.List.Count; i++)
            {
                UploadFileModel model = (UploadFileModel)list.List[i];
                string a_id = "thumb_sub-0" + (i + 1);
                string a_href = "#image_sub-0" + (i + 1);  //  锚链到大图的divId
                string imgPath = null;
                if (!string.IsNullOrEmpty(model.ThumbnailImagePath))
                    imgPath = "/uploadfiles/image/" + model.ThumbnailImagePath;
                else
                    imgPath = GetUploadFileDefaultImage(model);
                //string imgpath = "/uploadfiles/image/" + (string.IsNullOrEmpty(model.ThumbnailImagePath) ? "default_slide_img.jpg" : model.ThumbnailImagePath); //缩略图
                sb.Append("<li class=\"slideshowItem\" id=\"ul_slide_item_" + i + "\"><a id=\"" + a_id + "\" href=\"" + a_href + "\" fileID=\"" + model.ID + "\" fileType=\"" + model.FileType + "\" fileName=\"/uploadfiles/media/" + model.Path + "\"><img src=\"" + imgPath + "\" alt=\"\" onerror='this.src=\"" + GetUploadFileDefaultImage(model) + "\"'/></a></li>");
            }
            return sb.ToString();
        }

        private string GetUploadFileDefaultImage(UploadFileModel model)
        {
            string rootDir = GetRootDir();
            string imageName = "default_slide_image";
            if (model.FileType == 2)
                imageName = "default_video";
            else if (model.FileType == 3)
                imageName = "default_audio";
            return string.Format("{0}/images/{1}.jpg", rootDir, imageName);
        }

        public string GetEventsTicketUrl()
        {
            // 返回值：<dt><a href="#"><img src="../images/btn_preordain.gif" alt="" /></a></dt>
            if (string.IsNullOrEmpty(this.EventsModel.TicketUrl))
                return "<br/>";
            else
                return string.Format("<br/><dt><a target='_blank' href='{0}'><img src='{1}/images/btn_preordain.gif' alt=''/></a></dt>", this.EventsModel.TicketUrl, GetRootDir());
        }

        public string GetSeriesEvents()
        {
            // 返回值：<div class="othercity"><span>该活动在其它城市：</span><a href="#">杭州 &gt;</a>、<a href="#">上海 &gt;</a>、<a href="#">广州 &gt;</a></div>
            string text = (this.LanguageID == (int)LanguageType.en) ? "Attend this event in: " : "该活动在其它城市：";
            EventsBLL bll = new EventsBLL(this.LanguageID);
            IList<EventsModel> series = bll.GetSeriesEvents(this.EventsModel.ID, false);
            if (series == null || series.Count == 0) return string.Empty;
            StringBuilder builder = new StringBuilder("<div class='othercity'><span>").Append(text).Append("</span>");
            int i = 0;
            foreach (EventsModel model in series)
            {
                if (i > 0)
                    builder.Append("、");

                DictionaryManageModel dmm = DictionaryUtil.GetCityByID(model.City.Value);
                string path = model.ID + ".html";
                builder.AppendFormat("<a href='{0}'>{1}&gt;</a>", path, (this.LanguageID == 2052 ? dmm.Cnname : dmm.Enname));

                i++;
            }
            builder.Append("</div>");

            return builder.ToString();
        }

        public string GetEventsFlash()
        {
            string flashUrl = string.Format("{0}/{1}?lang={2}&eid={3}", GetRootDir(), "swf/Gallery.swf", this.LanguageID, this.EventsModel.ID.Value);
            StringBuilder builder = new StringBuilder("<div id=\"topstory\"></div>");
            builder.Append("<script type=\"text/javascript\">");
            builder.Append("var fo = new FlashObject(\"" + flashUrl + "\", \"Flash\", \"742\", \"356\" , \"9\", \"#ffffff\");");
            builder.Append("fo.addParam(\"menu\", \"false\");");
            builder.Append("fo.addParam(\"scale\", \"noscale\");");
            builder.Append("fo.addParam(\"wmode\", \"transparent\");");
            builder.Append("fo.write(\"topstory\");");
            builder.Append("</script>");

            return builder.ToString();
        }
    }
}
